<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Cms\Repository;

use Cms\Entity\Cms;
use Cms\Entity\CmsClass;
use Cms\Repository\QuerySearch\CmsSearch;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Doctrine\ORM\QueryBuilder;

class CmsRepository extends EntityRepository
{
    /**
     * 后台文章列表
     * @param array $search
     * @return \Doctrine\ORM\Query
     */
    public function findListCms($search = [])
    {
        $query = $this->getEntityManager()->createQueryBuilder()
            ->select('c', 'a.cmsClassName')
            ->from(Cms::class, 'c')
            ->leftJoin(CmsClass::class, 'a', Join::WITH, 'c.cmsClassId=a.cmsClassId')
            ->orderBy('c.cmsSort', 'ASC')
            ->addOrderBy('c.cmsId', 'DESC');

        $query = CmsSearch::querySearchData($search, $query);

        return $query->getQuery();
    }

    /*==============================================下面为前台调用==============================================*/
    /**
     * 前台文章列表
     * @param $cmsClassId
     * @param array $search
     * @return \Doctrine\ORM\Query
     */
    public function shopListCms($cmsClassId, $search = [])
    {
        $query = $this->getEntityManager()->createQueryBuilder()
            ->select('c', 'a.cmsClassName')
            ->from(Cms::class, 'c')
            ->leftJoin(CmsClass::class, 'a', Join::WITH, 'c.cmsClassId=a.cmsClassId')
            ->where('c.cmsClassId = :cmsClassId')->setParameter('cmsClassId', $cmsClassId)
            ->orderBy('c.cmsSort', 'ASC')
            ->addOrderBy('c.cmsId', 'DESC');

        return $query->getQuery();
    }

    /**
     * 前台首页新闻功能
     * @param int $newsNum
     * @return int|mixed|string
     */
    public function findShopIndexNews($newsNum = 10)
    {
        $query = $this->getEntityManager()->createQueryBuilder()
            ->select('c', 'a.cmsClassName', 'a.cmsClassId')
            ->from(Cms::class, 'c')
            ->innerJoin(CmsClass::class, 'a', Join::WITH, 'c.cmsClassId=a.cmsClassId')
            ->where('a.indexNews = :indexNews')->setParameter('indexNews', 1)
            ->andWhere('c.cmsState = :cmsState')->setParameter('cmsState', 1)
            ->orderBy('c.cmsSort', 'ASC')
            ->addOrderBy('c.cmsId', 'DESC')
            ->setMaxResults($newsNum);

        return $query->getQuery()->getResult();
    }
}